﻿using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.Crmf;
using RestSharp;
using StackExchange.Redis;
using System.Runtime.Intrinsics.Arm;
using Utility;

namespace HuaRunInterface.Comm
{
    public class Global
    {
        #region 工商业

        /// <summary>
        /// 协议类型
        /// </summary>
        private static List<KeyValueModel> protocolTypes_Industry;
        /// <summary>
        /// 进气方向
        /// </summary>
        private static List<KeyValueModel> gasEnterDirection_Industry;
        /// <summary>
        /// 通信方式
        /// </summary>
        private static List<KeyValueModel> communicationType_Industry;
        /// <summary>
        /// 气表分类
        /// </summary>
        private static List<KeyValueModel> meterClassify_Industry;
        /// <summary>
        /// 阀门状态
        /// </summary>
        private static List<KeyValueModel> valveState_Industry;
        /// <summary>
        /// 表具类型
        /// </summary>
        private static List<KeyValueModel> meterType_Industry;
        /// <summary>
        /// 设备类型
        /// </summary>
        private static List<KeyValueModel> deviceType_Industry;
        /// <summary>
        /// 计费方式
        /// </summary>
        private static List<KeyValueModel> chargingType_Industry;
        public static List<KeyValueModel> ProtocolTypes_Industry
        {
            get
            {
                if (protocolTypes_Industry == null)
                {
                    protocolTypes_Industry = new List<KeyValueModel>();
                    protocolTypes_Industry.Add(new KeyValueModel() { Key = "20203", Value = "华润工商业标准协议" });
                    protocolTypes_Industry.Add(new KeyValueModel() { Key = "99999", Value = "系统接入协议" });
                }
                return protocolTypes_Industry;
            }
        }

        public static List<KeyValueModel> GasEnterDirection_Industry
        {
            get
            {
                if (gasEnterDirection_Industry == null)
                {
                    gasEnterDirection_Industry = new List<KeyValueModel>();
                    gasEnterDirection_Industry.Add(new KeyValueModel() { Key = "01", Value = "左进气" });
                    gasEnterDirection_Industry.Add(new KeyValueModel() { Key = "02", Value = "右进气" });
                    gasEnterDirection_Industry.Add(new KeyValueModel() { Key = "03", Value = "上进气" });
                    gasEnterDirection_Industry.Add(new KeyValueModel() { Key = "04", Value = "下进气" });
                    gasEnterDirection_Industry.Add(new KeyValueModel() { Key = "05", Value = "未知" });
                }
                return gasEnterDirection_Industry;
            }
        }

        public static List<KeyValueModel> CommunicationType_Industry
        {
            get
            {
                if (communicationType_Industry == null)
                {
                    communicationType_Industry = new List<KeyValueModel>();
                    communicationType_Industry.Add(new KeyValueModel() { Key = "1", Value = "中国移动OneNet" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "2", Value = "中国联通" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "3", Value = "中国电信AEP（profile）" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "4", Value = "中国电信OC" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "5", Value = "中国电信AEP（透传）" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "6", Value = "扩频双向冒泡通讯" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "7", Value = "扩频Lora双向通讯" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "8", Value = "TCP长连" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "9", Value = "TCP短连" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "10", Value = "UDP" });
                    communicationType_Industry.Add(new KeyValueModel() { Key = "11", Value = "FSK组网" });
                }
                return communicationType_Industry;
            }
        }

        public static List<KeyValueModel> MeterClassify_Industry
        {
            get
            {
                if (meterClassify_Industry == null)
                {
                    meterClassify_Industry = new List<KeyValueModel>();
                    meterClassify_Industry.Add(new KeyValueModel() { Key = "28", Value = "质量流量计" });
                    meterClassify_Industry.Add(new KeyValueModel() { Key = "29", Value = "旋进旋涡流量计" });
                    meterClassify_Industry.Add(new KeyValueModel() { Key = "30", Value = "超声波流量计" });
                    meterClassify_Industry.Add(new KeyValueModel() { Key = "31", Value = "涡轮流量计" });
                    meterClassify_Industry.Add(new KeyValueModel() { Key = "32", Value = "腰轮流量计" });
                    meterClassify_Industry.Add(new KeyValueModel() { Key = "33", Value = "罗茨流量计" });
                    meterClassify_Industry.Add(new KeyValueModel() { Key = "34", Value = "膜式燃气表" });
                    meterClassify_Industry.Add(new KeyValueModel() { Key = "35", Value = "超声波燃气表" });
                    meterClassify_Industry.Add(new KeyValueModel() { Key = "36", Value = "热式燃气表" });
                }
                return meterClassify_Industry;
            }
        }

        public static List<KeyValueModel> ValveState_Industry
        {
            get
            {
                if (valveState_Industry == null)
                {
                    valveState_Industry = new List<KeyValueModel>();
                    valveState_Industry.Add(new KeyValueModel() { Key = "0", Value = "开启" });
                    valveState_Industry.Add(new KeyValueModel() { Key = "1", Value = "关闭" });
                    valveState_Industry.Add(new KeyValueModel() { Key = "2", Value = "开不到位" });
                    valveState_Industry.Add(new KeyValueModel() { Key = "3", Value = "关不到位" });
                    valveState_Industry.Add(new KeyValueModel() { Key = "4", Value = "未知" });
                    valveState_Industry.Add(new KeyValueModel() { Key = "5", Value = "异常" });
                    valveState_Industry.Add(new KeyValueModel() { Key = "6", Value = "授权开阀" });
                    valveState_Industry.Add(new KeyValueModel() { Key = "7", Value = "无计量关阀" });
                    valveState_Industry.Add(new KeyValueModel() { Key = "8", Value = "失联关阀" });
                    valveState_Industry.Add(new KeyValueModel() { Key = "9", Value = "无阀门" });
                }
                return valveState_Industry;
            }
        }

        public static List<KeyValueModel> MeterType_Industry
        {
            get
            {
                if (meterType_Industry == null)
                {
                    meterType_Industry = new List<KeyValueModel>();
                    meterType_Industry.Add(new KeyValueModel() { Key = "4003", Value = "腰轮流量计" });
                    meterType_Industry.Add(new KeyValueModel() { Key = "4004", Value = "涡轮流量计" });
                    meterType_Industry.Add(new KeyValueModel() { Key = "4006", Value = "超声流量计" });
                    meterType_Industry.Add(new KeyValueModel() { Key = "4007", Value = "罗茨流量计" });
                    meterType_Industry.Add(new KeyValueModel() { Key = "4008", Value = "膜式燃气表" });
                    meterType_Industry.Add(new KeyValueModel() { Key = "4009", Value = "超声燃气表" });
                }
                return meterType_Industry;
            }
        }

        public static List<KeyValueModel> DeviceType_Industry
        {
            get
            {
                if (deviceType_Industry == null)
                {
                    deviceType_Industry = new List<KeyValueModel>();
                    deviceType_Industry.Add(new KeyValueModel() { Key = "10", Value = "一体式物联网流量计" });
                    deviceType_Industry.Add(new KeyValueModel() { Key = "11", Value = "一体式后台结算物联网流量计" });
                    deviceType_Industry.Add(new KeyValueModel() { Key = "12", Value = "后台结算物联网控制器" });
                    deviceType_Industry.Add(new KeyValueModel() { Key = "13", Value = "物联网采集器（RTU）" });
                    deviceType_Industry.Add(new KeyValueModel() { Key = "14", Value = "一体式表端结算物联网流量计" });
                    deviceType_Industry.Add(new KeyValueModel() { Key = "15", Value = "表端结算物联网控制器" });
                }
                return deviceType_Industry;
            }
        }

        public static List<KeyValueModel> ChargingType_Industry
        {
            get
            {
                if (chargingType_Industry == null)
                {
                    chargingType_Industry = new List<KeyValueModel>();
                    chargingType_Industry.Add(new KeyValueModel() { Key = "1", Value = "表端计费" });
                    chargingType_Industry.Add(new KeyValueModel() { Key = "2", Value = "中心计费" });
                }
                return chargingType_Industry;
            }
        }
        #endregion
        #region 民用
        /// <summary>
        /// 协议类型
        /// </summary>
        private static List<KeyValueModel> protocolTypes;
        /// <summary>
        /// 进气方向
        /// </summary>
        private static List<KeyValueModel> gasEnterDirection;
        /// <summary>
        /// 通信方式
        /// </summary>
        private static List<KeyValueModel> communicationType;
        /// <summary>
        /// 气表分类
        /// </summary>
        private static List<KeyValueModel> meterClassify;
        /// <summary>
        /// 阀门状态
        /// </summary>
        private static List<KeyValueModel> valveState;
        /// <summary>
        /// 表具类型
        /// </summary>
        private static List<KeyValueModel> meterType;
        /// <summary>
        /// 设备类型
        /// </summary>
        private static List<KeyValueModel> deviceType;
        /// <summary>
        /// 计费方式
        /// </summary>
        private static List<KeyValueModel> chargingType;

        public static List<KeyValueModel> ProtocolTypes
        {
            get
            {
                if (protocolTypes == null)
                {
                    protocolTypes = new List<KeyValueModel>();
                    protocolTypes.Add(new KeyValueModel() { Key = "10100", Value = "华润标准协议" });
                    protocolTypes.Add(new KeyValueModel() { Key = "10266", Value = "B_NB-IoT" });
                    protocolTypes.Add(new KeyValueModel() { Key = "9999", Value = "系统接入协议" });
                    protocolTypes.Add(new KeyValueModel() { Key = "10267", Value = "千嘉NB非标准协议" });
                }
                return protocolTypes;
            }
        }

        public static List<KeyValueModel> GasEnterDirection
        {
            get
            {
                if (gasEnterDirection == null)
                {
                    gasEnterDirection = new List<KeyValueModel>();
                    gasEnterDirection.Add(new KeyValueModel() { Key = "01", Value = "左进气" });
                    gasEnterDirection.Add(new KeyValueModel() { Key = "02", Value = "右进气" });
                    gasEnterDirection.Add(new KeyValueModel() { Key = "03", Value = "上进气" });
                    gasEnterDirection.Add(new KeyValueModel() { Key = "04", Value = "下进气" });
                    gasEnterDirection.Add(new KeyValueModel() { Key = "05", Value = "未知" });
                }
                return gasEnterDirection;
            }
        }

        public static List<KeyValueModel> CommunicationType
        {
            get
            {
                if (communicationType == null)
                {
                    communicationType = new List<KeyValueModel>();
                    communicationType.Add(new KeyValueModel() { Key = "1", Value = "中国移动OneNet" });
                    communicationType.Add(new KeyValueModel() { Key = "2", Value = "中国联通" });
                    communicationType.Add(new KeyValueModel() { Key = "3", Value = "中国电信AEP（profile）" });
                    communicationType.Add(new KeyValueModel() { Key = "4", Value = "中国电信OC" });
                    communicationType.Add(new KeyValueModel() { Key = "5", Value = "中国电信AEP（透传）" });
                    communicationType.Add(new KeyValueModel() { Key = "6", Value = "扩频双向冒泡通讯" });
                    communicationType.Add(new KeyValueModel() { Key = "7", Value = "扩频Lora双向通讯" });
                    communicationType.Add(new KeyValueModel() { Key = "8", Value = "TCP长连" });
                    communicationType.Add(new KeyValueModel() { Key = "9", Value = "TCP短连" });
                    communicationType.Add(new KeyValueModel() { Key = "10", Value = "UDP" });
                    communicationType.Add(new KeyValueModel() { Key = "11", Value = "FSK组网" });
                }
                return communicationType;
            }
        }

        public static List<KeyValueModel> MeterClassify
        {
            get
            {
                if (meterClassify == null)
                {
                    meterClassify = new List<KeyValueModel>();
                    meterClassify.Add(new KeyValueModel() { Key = "28", Value = "质量流量计" });
                    meterClassify.Add(new KeyValueModel() { Key = "29", Value = "旋进旋涡流量计" });
                    meterClassify.Add(new KeyValueModel() { Key = "30", Value = "超声波流量计" });
                    meterClassify.Add(new KeyValueModel() { Key = "31", Value = "涡轮流量计" });
                    meterClassify.Add(new KeyValueModel() { Key = "32", Value = "腰轮流量计" });
                    meterClassify.Add(new KeyValueModel() { Key = "33", Value = "罗茨流量计" });
                    meterClassify.Add(new KeyValueModel() { Key = "34", Value = "膜式燃气表" });
                    meterClassify.Add(new KeyValueModel() { Key = "35", Value = "超声波燃气表" });
                    meterClassify.Add(new KeyValueModel() { Key = "36", Value = "热式燃气表" });
                }
                return meterClassify;
            }
        }

        public static List<KeyValueModel> ValveState
        {
            get
            {
                if (valveState == null)
                {
                    valveState = new List<KeyValueModel>();
                    valveState.Add(new KeyValueModel() { Key = "0", Value = "开启" });
                    valveState.Add(new KeyValueModel() { Key = "1", Value = "关闭" });
                    valveState.Add(new KeyValueModel() { Key = "2", Value = "开不到位" });
                    valveState.Add(new KeyValueModel() { Key = "3", Value = "关不到位" });
                    valveState.Add(new KeyValueModel() { Key = "4", Value = "未知" });
                    valveState.Add(new KeyValueModel() { Key = "5", Value = "异常" });
                    valveState.Add(new KeyValueModel() { Key = "6", Value = "授权开阀" });
                    valveState.Add(new KeyValueModel() { Key = "7", Value = "无计量关阀" });
                    valveState.Add(new KeyValueModel() { Key = "8", Value = "失联关阀" });
                    valveState.Add(new KeyValueModel() { Key = "9", Value = "无阀门" });
                }
                return valveState;
            }
        }

        public static List<KeyValueModel> MeterType
        {
            get
            {
                if (meterType == null)
                {
                    meterType = new List<KeyValueModel>();
                    meterType.Add(new KeyValueModel() { Key = "1001", Value = "NB-IoT标准表" });
                    meterType.Add(new KeyValueModel() { Key = "1101", Value = "NB-IoT非标准表" });
                    meterType.Add(new KeyValueModel() { Key = "2001", Value = "LORA扩频(标准表)" });
                    meterType.Add(new KeyValueModel() { Key = "2201", Value = "LORA扩频(非标准表)" });
                    meterType.Add(new KeyValueModel() { Key = "3001", Value = "4G物联表(非标准表)" });
                    meterType.Add(new KeyValueModel() { Key = "3101", Value = "GPRS(2G)物联表(非标准)" });
                }
                return meterType;
            }
        }

        public static List<KeyValueModel> DeviceType
        {
            get
            {
                if (deviceType == null)
                {
                    deviceType = new List<KeyValueModel>();
                    deviceType.Add(new KeyValueModel() { Key = "1", Value = "集中器" });
                    deviceType.Add(new KeyValueModel() { Key = "5", Value = "RTU设备" });
                }
                return deviceType;
            }
        }

        public static List<KeyValueModel> ChargingType
        {
            get
            {
                if (chargingType == null)
                {
                    chargingType = new List<KeyValueModel>();
                    chargingType.Add(new KeyValueModel() { Key = "1", Value = "表端计费" });
                    chargingType.Add(new KeyValueModel() { Key = "2", Value = "中心计费" });
                }
                return chargingType;
            }
        }


        #endregion
        public static IConfiguration Configuration { get; set; }

        private static string _Token;
        public static string Token
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_Token))
                    GetAccessToken();
                return _Token;
            }
            set
            {
                _Token = value;
            }
        }
        private static string _DomainId;
        public static string DomainId
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_DomainId))
                {
                    GetCompanyInfo();
                }
                return _DomainId;
            }
            set
            {
                _DomainId = value;
            }
        }


        public static string GetToken()
        {
            var options = new RestClientOptions()
            {
                MaxTimeout = -1,
            };
            var client = new RestClient(options);
            var request = new RestRequest(new Uri(Global.Configuration["AppSettings:TokenUrl"]), Method.Post);
            request.AddHeader("Content-Type", "multipart/form-data;charset=utf-8");
            request.AlwaysMultipartFormData = true;
            request.AddParameter("client_id", $"{Global.Configuration["AppSettings:Client_Id"]}");
            request.AddParameter("client_secret", $"{Global.Configuration["AppSettings:Client_Secret"]}");
            request.AddParameter("longTokenFlag", "Y");
            request.AddParameter("grant_type", "client_credentials");
            RestResponse response = client.Execute(request);
            return response.Content;
        }

        public static string CommRest(string url, string authorization, string bodyValue)
        {
            var options = new RestClientOptions()
            {
                MaxTimeout = -1,
            };
            var client = new RestClient(options);
            var request = new RestRequest(new Uri(url), Method.Post);
            request.AddHeader("authorization", authorization);
            request.AddHeader("Content-Type", "application/json;charset=utf-8");
            var body = @"{}";
            request.AddParameter("application/json;charset=utf-8", body, ParameterType.RequestBody);
            RestResponse response = client.Execute(request);
            return response.Content;
        }

        public static bool GetAccessToken()
        {
            bool re = false;

            try
            {
                string result = GetToken();
                if (!string.IsNullOrEmpty(result))
                {
                    Utility.WriteLog.WriteLogFile($"Get Access Token :{result}");
                    Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                    Token = json["access_token"].ToString();
                    re = true;
                    if (string.IsNullOrWhiteSpace(Token))
                    {
                        Token = null;
                        Utility.WriteLog.WriteLogFile($"Get Access Token :{json["error"].ToString()}");
                        re = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.WriteLog.WriteLogFile($"Get Access Token :{ex.Message}\r\n{ex.InnerException.Message}");
                re = false;
            }
            return re;
        }

        public static bool GetCompanyInfo()
        {
            bool re = false;
            try
            {
                string baseUrl = Global.Configuration["AppSettings:BaseUrl"];
                string result = Utility.HttpService.Post("{}", $"{baseUrl}/eciot-openapi/area/getAllCompanyForAreaConfig", 50, "application/json;charset=utf-8", $"Bearer {Token}");
                if (!string.IsNullOrWhiteSpace(result))
                {
                    Utility.WriteLog.WriteLogFile($"Get CompanyInfo  :{result}");

                    Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                    if (json["code"].ToString() == "200")
                    {
                        string cName = Global.Configuration["AppSettings:CompanyName"];
                        List<CompanyInfoModel> cs = json["body"].ToString().JSONStringToList<CompanyInfoModel>();
                        DomainId = cs.Where(p => p.companyName == cName).FirstOrDefault().domainId;
                        re = true;
                    }
                    else
                    {
                        Utility.WriteLog.WriteLogFile($"Get CompanyInfo :{json["msg"].ToString()}");
                        re = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.WriteLog.WriteLogFile($"Get CompanyInfo  :{ex.Message}\r\n{ex.InnerException.Message}");
                re = false;
            }
            return re;
        }

        public static bool RTURegister(RTURegisterModel value, ref string msg)
        {
            bool re = false;
            string baseUrl = Global.Configuration["AppSettings:BaseUrl"];
            string result = Utility.HttpService.Post(value.SerializerObjectToString(), $"{baseUrl}/eciot-openapi/rtu/batchAddRtuList", 40, "application/json;charset=utf-8", $"Bearer {Token}");
            Utility.WriteLog.WriteLogFile($"RTU Register Post Result:{result} ; Data :{value.SerializerObjectToString()}");
            if (!string.IsNullOrEmpty(result))
            {
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                if (json["code"].ToString() == "200")
                {
                    re = true;
                }
                else
                {
                    msg = json["msg"].ToString();
                    Utility.WriteLog.WriteLogFile($"RTU Register :{msg}");
                    re = false;
                }
            }
            return re;
        }

        public static bool RTURegister(List<RTURegisterModel> value, ref string msg)
        {
            bool re = false;
            string baseUrl = Global.Configuration["AppSettings:BaseUrl"];
            string result = Utility.HttpService.Post(value.SerializerObjectToString(), $"{baseUrl}/eciot-openapi/rtu/batchAddRtuList", 40, "application/json;charset=utf-8", $"Bearer {Token}");
            Utility.WriteLog.WriteLogFile($"RTU Register Post Result:{result} ; Data :{value.SerializerObjectToString()}");
            if (!string.IsNullOrEmpty(result))
            {
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                if (json["code"].ToString() == "200")
                {
                    re = true;
                }
                else
                {
                    msg = json["msg"].ToString();
                    Utility.WriteLog.WriteLogFile($"RTU Register :{msg}");
                    re = false;
                }
            }
            return re;
        }

        public static bool RTUDelete(RTUDeleteModel value, ref string msg)
        {
            bool re = false;

            string baseUrl = Global.Configuration["AppSettings:BaseUrl"];
            string result = Utility.HttpService.Post(value.SerializerObjectToString(), $"{baseUrl}/eciot-openapi/rtu/delRtu", 40, "application/json;charset=utf-8", $"Bearer {Token}");
            Utility.WriteLog.WriteLogFile($"RTU Delete Post Result:{result} ; Data :{value.SerializerObjectToString()}");
            if (!string.IsNullOrEmpty(result))
            {
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                if (json["code"].ToString() == "200")
                {
                    re = true;
                }
                else
                {
                    msg = json["msg"].ToString();
                    Utility.WriteLog.WriteLogFile($"RTU Delete :{msg}");
                    re = false;
                }
            }
            return re;
        }

        public static bool MeterRegister(MeterRegisterModel value, ref string msg)
        {
            bool re = false;

            string baseUrl = Global.Configuration["AppSettings:BaseUrl"];

            string result = Utility.HttpService.Post(value.SerializerObjectToString(), $"{baseUrl}/eciot-openapi/industryMeter/batchAdd", 40, "application/json;charset=utf-8", $"Bearer {Token}");
            Utility.WriteLog.WriteLogFile($"Meter Register Post Result:{result} ; Data :{value.SerializerObjectToString()}");
            if (!string.IsNullOrEmpty(result))
            {
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                if (json["code"].ToString() == "200")
                {
                    re = true;
                }
                else
                {
                    msg = json["msg"].ToString();
                    Utility.WriteLog.WriteLogFile($"Meter Register :{msg}");
                    re = false;
                }
            }
            return re;
        }

        public static bool MeterRegister(List<MeterRegisterModel> value, ref string msg)
        {
            bool re = false;

            string baseUrl = Global.Configuration["AppSettings:BaseUrl"];

            string result = Utility.HttpService.Post(value.SerializerObjectToString(), $"{baseUrl}/eciot-openapi/industryMeter/batchAdd", 40, "application/json;charset=utf-8", $"Bearer {Token}");
            Utility.WriteLog.WriteLogFile($"Meter Register Post Result:{result} ; Data :{value.SerializerObjectToString()}");
            if (!string.IsNullOrEmpty(result))
            {
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                if (json["code"].ToString() == "200")
                {
                    re = true;
                }
                else
                {
                    msg = json["msg"].ToString();
                    Utility.WriteLog.WriteLogFile($"Meter Register :{msg}");
                    re = false;
                }
            }
            return re;
        }

        public static bool MeterDelete(MeterDeleteModel value, ref string msg)
        {
            bool re = false;
            string baseUrl = Global.Configuration["AppSettings:BaseUrl"];

            string result = Utility.HttpService.Post(value.SerializerObjectToString(), $"{baseUrl}/eciot-openapi/industryMeter/delMeter", 40, "application/json;charset=utf-8", $"Bearer {Token}");
            Utility.WriteLog.WriteLogFile($"Meter Delete Post Result:{result} ; Data :{value.SerializerObjectToString()}");
            if (!string.IsNullOrEmpty(result))
            {
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                if (json["code"].ToString() == "200")
                {
                    re = true;
                }
                else
                {
                    msg = json["msg"].ToString();
                    Utility.WriteLog.WriteLogFile($"Meter Delete :{msg}");
                    re = false;
                }
            }
            return re;
        }

        public static bool CommonSend(string apiAddress, object value, ref string msg)
        {
            bool re = false;

            string baseUrl = Global.Configuration["AppSettings:BaseUrl"];

            string result = Utility.HttpService.Post(value.SerializerObjectToString(), $"{baseUrl}/{apiAddress}", 40, "application/json;charset=utf-8", $"Bearer {Token}");
            Utility.WriteLog.WriteLogFile($"Common Send Result:{result} ; Data :{value.SerializerObjectToString()} ; Address:{apiAddress}");
            if (!string.IsNullOrEmpty(result))
            {
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                if (json["code"].ToString() == "200")
                {
                    re = true;
                }
                else
                {
                    msg = json["msg"].ToString();
                    Utility.WriteLog.WriteLogFile($"Common Send Error Msg :{msg}");
                    re = false;
                }
            }
            return re;
        }

        public static bool GetAreaCode()
        {
            bool re = false;
            string baseUrl = Global.Configuration["AppSettings:BaseUrl"];
            string result = Utility.HttpService.Post("{}", $"{baseUrl}/eciot-openapi/area/page", 50, "application/json;charset=utf-8", $"Bearer {Token}");
            if (!string.IsNullOrWhiteSpace(result))
            {
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(result);
                if (json["code"].ToString() == "200")
                {
                    re = true;
                }
                else
                {
                    Utility.WriteLog.WriteLogFile($"Get area code :{json["msg"].ToString()}");
                    re = false;
                }
            }
            return re;
        }


        public static string HttpIOTSend(string apiInterface, string body)
        {
            string result = "";
            try
            {
                string baseUrl = Global.Configuration["AppSettings:IOTBaseUrl"];
                string loginName = Global.Configuration["AppSettings:IOTName"];
                string pwd = Global.Configuration["AppSettings:IOTPwd"];
                string loginUrl = $"api/Conf/Account/Login?loginName={loginName}&pwd={pwd}";
                string loginResult = HttpService.Post("", string.Format("{0}/{1}", baseUrl, loginUrl), 50, "");
                if (!string.IsNullOrWhiteSpace(loginResult))
                {
                    JObject obj = JObject.Parse(loginResult);
                    if (obj["State"].ToString() == "success")
                    {
                        string token = obj["Data"]["token"].ToString();
                        WriteLog.WriteLogFile("http iot send : " + body + "\r\n; api interface : " + apiInterface);

                        result = HttpService.Post(body, string.Format("{0}/{1}", baseUrl, apiInterface), token, 50);
                        WriteLog.WriteLogFile("http iot send result : " + result);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteExceptionFile("Http IOT Send Exception : " + ex.Message + "\r\n" + ex.StackTrace);
            }
            return result;
        }
    }

    public class MeterDeleteModel
    {
        public string sequence { get; set; }//String  Y 业务序列
        public string domainId { get; set; }//String  N 公司编码（通过公司查询获取）
        public string meterCode { get; set; }//String  N 表具编码
        public string uniqueDeviceIdentifier { get; set; }//String  Y 设备唯一标示符(表具注册时，通过回调方法返回的值)
    }

    public class MeterRegisterModel
    {
        public string? sequence { get; set; }// nvarchar(32),
        public string? domainId { get; set; }// nvarchar(32),
        public string? orgId { get; set; }// nvarchar(32),
        public string? meterCode { get; set; }// nvarchar(32),
        public string? deviceType { get; set; }//  nvarchar(32),
        public string? conMeterCode { get; set; }// nvarchar(32),
        public string? protocolTypeCode { get; set; }// nvarchar(32),
        public string? modelCode { get; set; }// nvarchar(32),
        public string? meterTypeCode { get; set; }// nvarchar(32),
        public string? mrFactoryCode { get; set; }// nvarchar(32),
        public string? meterFactoryCode { get; set; }// nvarchar(32),
        public decimal? baseNo { get; set; }// decimal (18,3),
        public string? installDate { get; set; }//  nvarchar(32),
        public string? inDirection { get; set; }// nvarchar(32),
        public string? commMode { get; set; }//  nvarchar(32),
        public string? installPostion { get; set; }//  nvarchar(300),
        public string? longitude { get; set; }// nvarchar(32),
        public string? latitude { get; set; }//  nvarchar(32),
        public string? nbImei { get; set; }//  nvarchar(32),
        public string? nbImsi { get; set; }// nvarchar(32),
        public string? appKey { get; set; }
        public string? appEui { get; set; }
        public string? devEui { get; set; }
        public int? valveStatus { get; set; }// int,
        public string meterCategory { get; set; }
        public string calcTypeCode { get; set; }
    }

    public class RTUDeleteModel
    {
        public string sequence { get; set; }//String  Y 业务序列
        public string domainId { get; set; }//String  Y 公司id（通过公司查询获取）
        public string uniqueDeviceIdentifier { get; set; }//String  Y 设备唯一标示符(RTU(控制器、采集器)注册时，通过回调方法返回的值)
    }

    public class RTURegisterModel
    {
        public string sequence { get; set; }//String  Y 业务序列
        public string domainId { get; set; }//String  Y 公司id
        public string deviceCode { get; set; }//String  Y 设备编码；（控制器、采集器编码）
        public string factoryCode { get; set; }//String  Y 生产厂家编码，默认为当前应用所属厂家（参考字典表）
        public string deviceType { get; set; }//String  Y 设备类型（参考字典表）
        public string protocolTypeCode { get; set; }//String  Y 协议类型（参考字典表）
        public string commMode { get; set; }//String  Y 通讯方式（参考字典表）
        public string nbImei { get; set; }//String  N 当表具类型为NB时，为必填
        public string nbImsi { get; set; }//String N   当表具类型为NB时，为必填
    }

    public class AuthenticationModel
    {
        public string client_id { get; set; }//String  Y 应用ID
        public string client_secret { get; set; }//String  Y 应用秘钥
        public string longTokenFlag { get; set; } = "Y";//String  Y 固定值:Y
        public string grant_type { get; set; } = "client_credentials";//String Y   固定值:client_credentials
    }

    public class CompanyInfoModel
    {
        public string companyName { get; set; }
        public string domainId { get; set; }
    }

    public class KeyValueModel
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }
}
